Page({
  data: {
    login: false,
    userInfo: {},
    fromData: [
      { water: 0 }  // 初始化今天已喝的水量
    ],
    dailyTarget: 1500,  // 每日目标
    weeklist: [],  // 一周的日期列表
    windowHeight: 0 , // 屏幕高度
    selectedTime: '09:00', // 用户选择的提醒时间，默认为上午9点
    dailyTargets: ['1500', '2000', '2500', '3000'], // 可选的每日目标列表
    selectedDailyTarget: 0, // 默认选中第一个目标
  },

  onLoad: function() {
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          windowHeight: res.windowHeight
        });
      }
    });

    // 初始化一周的日期列表
    this.setData({
      weeklist: this.generateWeekList()
    });

    // 加载当天的饮水数据
    const today = this.getTodayDate();
    wx.getStorage({
      key: today,
      success: (res) => {
        this.setData({
          fromData: [res.data]
        });
      },
      fail: () => {
        this.setData({
          fromData: [{ water: 0 }]
        });
      }
    });

    // 设置初始提醒
    this.setCustomReminder()
  },

  generateWeekList: function() {
    const weekDays = ["日", "一", "二", "三", "四", "五", "六"];
    const date = new Date();
    let weekList = [];
    for (let i = 0; i < 7; i++) {
      date.setDate(date.getDate() + i);
      const day = date.getDate();
      const weekDay = weekDays[date.getDay()];
      weekList.push(`${weekDay} ${day}`);
    }
    return weekList;
  },

  getTodayDate: function() {
    const date = new Date();
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  updateWaterData: function(amount) {
    const newWaterAmount = this.data.fromData[0].water + amount;
    if (newWaterAmount < 0) return;  // 避免负数
    this.setData({
      'fromData[0].water': newWaterAmount
    });

    // 保存数据到本地存储
    const today = this.getTodayDate();
    wx.setStorage({
      key: today,
      data: { water: newWaterAmount }
    });
  },

  getDrink1: function() {
    this.updateWaterData(250);
  },

  getDrink2: function() {
    this.updateWaterData(350);
  },

  getDrink3: function() {
    this.updateWaterData(500);
  },

  getDrink4: function() {
    this.updateWaterData(1000);
  },

  clear: function() {
    // 清空当天的数据
    wx.showModal({
      title: '清空数据',
      content: '确定要清空今天的饮水数据吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            fromData: [{ water: 0 }]
          });

          const today = this.getTodayDate();
          wx.removeStorage({
            key: today
          });

          wx.showToast({
            title: '清空成功',
            icon: 'success',
            duration: 2000
          });
        }
      }
    });
  },

  // 监听时间选择器变化
  bindTimeChange: function(e) {
    this.setData({
      selectedTime: e.detail.value
    });
    // 更新提醒时间
    this.setCustomReminder();
  },

  // 转换时间字符串为Date对象
  stringToDate: function(timeString) {
    const [hour, minute] = timeString.split(":");
    const today = new Date();
    today.setHours(parseInt(hour, 10), parseInt(minute, 10), 0);
    return today;
  },

  // 取消所有本地通知
  cancelAllLocalNotifications: function() {
    wx.getLocalNotifications({
      success: (res) => {
        // 遍历所有通知并取消
        res.forEach((notification) => {
          wx.removeLocalNotification({
            taskId: notification.taskId
          });
        });
      }
    });
  },

  // 设置自定义时间的提醒
  setCustomReminder: function() {
    // 首先取消所有已设置的提醒
    this.cancelAllLocalNotifications();

    // 转换时间字符串为Date对象
    const reminderTime = this.stringToDate(this.data.selectedTime);
    
    // 设置新的提醒
    wx.setLocalNotification({
      title: '喝水提醒',
      content: '到时间喝水啦！',
      time: reminderTime.getTime() // 转换为时间戳
    });
  },

  // 将时间字符串转换为Date对象
  stringToDate: function(timeString) {
    const [hour, minute] = timeString.split(":");
    const today = new Date();
    today.setHours(parseInt(hour, 10), parseInt(minute, 10), 0);
    return today;
  },

  showTimePicker: function() {
    this.setData({
      timePickerVisible: true
    });
  },

  hideTimePicker: function() {
    this.setData({
      timePickerVisible: false
    });
  },

  confirmTime: function() {
    // 用户点击确定后，隐藏时间选择器，并保存选择的时间
    this.hideTimePicker();
  },
  // 处理每日目标选择器变化的事件
  bindDailyTargetChange: function(e) {
    const index = e.detail.value;
    this.setData({
      selectedDailyTarget: index,
      dailyTarget: this.data.dailyTargets[index]
    });
  },

  bindDailyTargetChange: function(e) {
    const index = e.detail.value; // 获取选择器变化后的索引
    const selectedTarget = this.data.dailyTargets[index]; // 根据索引获取选中的值
    this.setData({
      selectedDailyTarget: index, // 更新 selectedDailyTarget
      dailyTarget: selectedTarget // 更新 dailyTarget 为选中的值
    });
  },
});

